/**
 * @a https://leetcode.cn/problems/longest-common-prefix/
 */

#include "common.h"
// 解法 统一比较
class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        int sz = strs.size();
        if(sz == 0) return "";
        if(sz == 1) return strs[0];
        int minlen = strs[0].size();
        for(int i = 0; i < sz - 1; ++i){
            minlen = minlen > strs[i + 1].size() ? strs[i + 1].size() : minlen;
        }
        string prefix = "";
        for(int i = 0; i < minlen; ++i){
            bool is_break = false;
            for(int j = 0; j < sz - 1; ++j){
                if(strs[j][i] != strs[j+1][i]){
                    is_break = true;
                    break;
                }
            }
            if(is_break) break;
            prefix.push_back(strs[0][i]);
        }
        return prefix;
    }
};


// 解法 两两比较
class Solution {
private:
        string getCommon(const string& s1, const string& s2){
            int sz = min(s1.size() ,s2.size());
            if(sz == 0) return "";
            string tmp = "";
            for(int i = 0; i < sz; ++i){
                if(s1[i] == s2[i])
                    tmp.push_back(s1[i]);
                else break;
            }
            return tmp;
        }
public:
    string longestCommonPrefix(vector<string>& strs) {
        string two_common = strs[0];
        for(int i = 0; i < strs.size() - 1; ++i){
            two_common = getCommon(two_common, strs[i+1]);
            // 优化：如果公共前缀已经为空，后续就没有比较的必要了
            if (two_common.empty()) {
                break;
            }
        }
        return two_common;
    }
};